package com.tanhua.server.service;


import com.tanhua.autoconfig.template.SmsTemplate;
import com.tanhua.domain.User;
import com.tanhua.dubbo.api.UserApi;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.utils.JwtUtils;
import com.tanhua.vo.ErrorResult;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserService {

    @Autowired
    private SmsTemplate smsTemplate;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @DubboReference
    private UserApi userApiImpl;



    public void sendCode(String phone) {
        //1.生成随机6位数
        //String code = RandomStringUtils.randomNumeric(6);
        String code = "123456";

        //2.调用template对象,发送验证码
        //smsTemplate.sendSms(phone,code);
        //3.将验证码存入redis
        redisTemplate.opsForValue().set("CHECK_CODE_" +phone,code, Duration.ofMinutes(5));

    }


    public Map loginVerification(String mobile, String code) {
        //从redis中获取code
        String redisCode = redisTemplate.opsForValue().get("CHECK_CODE_" + mobile);
        //判断code是否存在,是否一致
        if (StringUtils.isEmpty(redisCode) || !redisCode.equals(code)){
            throw new BusinessException(ErrorResult.loginError());
        }
        //定义变量,false为不是新用户
        boolean isNew = false;
        User user = userApiImpl.findByPhone(mobile);
        if (user == null){
            user = new User();
            user.setMobile(mobile);
            user.setPassword(DigestUtils.md5Hex("123456"));
            Long id = userApiImpl.save(user);
            //获取刚刚存入的用户的id
            user.setId(id);
            //将用户设置为新用户
            isNew = true;
        }
        //用id和手机号生成token
        Map tokenMap = new HashMap<String,Object>();
        tokenMap.put("id",user.getId());
        tokenMap.put("mobile",mobile);
        String token = JwtUtils.getToken(tokenMap);

        //封装数据返回
        Map resule = new HashMap();
        resule.put("token",token);
        resule.put("isNew",isNew);

        return resule;
    }
}
